package org.coone.netproxy.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.coone.netproxy.exception.NetProxyException;
import org.coone.netproxy.log.Logger;
import org.coone.netproxy.log.LoggerFactory;
import org.coone.netproxy.utils.StringUtil;

public class NetProxyConfig {

	private static Logger logger = LoggerFactory.getLogger(NetProxyConfig.class);
	
	private static NetProxyConfig dbProxyConfig;
	
	private static Properties properties = new Properties();
	
	private NetProxyConfig() {}
	
	public static NetProxyConfig getInstance() {
		if(null == dbProxyConfig) {
			dbProxyConfig = new NetProxyConfig();
		}
		return dbProxyConfig;
	}
	
	public void loadProperties(String fileName) {
		if (StringUtil.isEmpty(fileName))
			throw new NetProxyException("DBProxyConfig name is null...");
		InputStream inputStream = null;
		try {
			inputStream = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(fileName);
			properties.load(inputStream);
		} catch (IOException e) {
			throw new NetProxyException("DBProxyConfig file load failed... "
					+ fileName);
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		if (properties == null)
			throw new RuntimeException("Properties file loading failed: "
					+ fileName);
	}

	public static Properties getProperties() {
		return properties;
	}

	public static void setProperties(Properties properties) {
		NetProxyConfig.properties = properties;
	}

	public String getProperty(String key) {
		System.out.println();
		
		return properties.getProperty(key).trim();
	}

	public String getProperty(String key, String defaultValue) {
		return properties.getProperty(key, defaultValue.trim());
	}
	
	public int getInt(String key, String defaultValue) {
		return Integer.valueOf(getProperty(key, defaultValue));
	}
	
	public boolean getBoolean(String key, String defaultValue) {
		return Boolean.valueOf(getProperty(key, defaultValue));
	}
}
